package com.dahuyou.netty.keepaliveAndIdle.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.text.SimpleDateFormat;
import java.util.Date;

//public class MyServerHandler extends ChannelInboundHandlerAdapter {
public class MyServerHandler extends IdleStateHandler {

    public MyServerHandler() {
        // 5秒钟没有read时间发生则触发idle
        super(8, 0, 0);
    }

    /**
     * 触发idle的回调方法
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        System.out.println("MyServerHandler.channelIdle...");
        // 如果是第一次read idle,就断开连接，当然具体业务中你可以通过判断其他类型的时间来做满足你业务要求的处理
        if (evt == IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT) {
            System.out.println("first idle check, just close connection");
            ctx.close();
            return;
        }
        super.channelIdle(ctx, evt);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[server 1]read msg: " + msg);
        super.channelRead(ctx, msg);
    }
}
